package com.wen.system.shiro.filter;

import cn.hutool.json.JSONUtil;
import com.wen.common.enums.CodeEnum;
import com.wen.common.utils.JwtUtil;
import com.wen.common.utils.ResponseResult;
import com.wen.system.jwt.JwtToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT HTTP AuthenticationFilter
 *
 * <p>
 *
 * @author devin <devinlive@163.com>
 * @version 1.0
 * @since 2023/7/21 13:19
 */
@Slf4j
@Component
public class AJwtFilter2 extends BasicHttpAuthenticationFilter {

    @Autowired
    JwtUtil jwtUtil;

    /**
     * 根据请求头JWT token的标头获取token值
     *
     * @param request
     * @return
     */
    @Override
    protected String getAuthzHeader(ServletRequest request) {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        String header = jwtUtil.getHeader();
        return httpRequest.getHeader(header);
    }

    /**
     * 1.如果用户经过身份验证，默认实现返回true。
     * 2.如果isLoginRequest返回false
     * 3.并且设置了“permissive”标志，也将返回true。
     * <p>
     * 返回true，shiro就直接允许访问url，返回false，shiro才会根据onAccessDenied的方法的返回值决定是否允许访问url
     *
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        System.out.println("isAccessAllowed ==> isAuthenticated :" + SecurityUtils.getSubject().isAuthenticated());
//        Subject subject = SecurityUtils.getSubject();
//        return null != subject && subject.isAuthenticated();
        // 有token返回false去验证，没有则放行，说明是游客 后面的请求会配合接口的访问权限来控制
        return !isLoginAttempt(request, response);
    }

    /**
     * 拒绝访问，响应json
     *
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        String token = getAuthzHeader(request);
        boolean loggedIn = false; //false by default or we wouldn't be in this method
        // 有token拒绝，token验证失败，封装失败消息给前端
        if (isLoginAttempt(request, response)) {
            loggedIn = executeLogin(request, response);
        }
        System.out.println("onAccessDenied ==>executeLogin isAuthenticated :" + SecurityUtils.getSubject().isAuthenticated());
        return loggedIn;

    }


    protected boolean executeLogin1(ServletRequest request, ServletResponse response) throws Exception {
        String jwt = this.getAuthzHeader(request);
        // 校验jwt
//        Claims claim = jwtUtil.getClaimByToken(jwt);
//        if (claim == null || jwtUtil.isTokenExpired(claim.getExpiration())) {
////            throw new AuthenticationException("token已失效，请重新登录");
//            // business
//            throw new CustomException(CodeEnum.USER_TOKEN_NOT_EXIST.getResultCode(),
//                    CodeEnum.USER_TOKEN_NOT_EXIST.getResultMsg());
//        }
//        AuthenticationToken token = createToken(request, response);
        // 提交给realm进行认证,如果错误他会抛出异常并被捕获,没有则代表认证成功，返回true
        SecurityUtils.getSubject().login(new JwtToken(jwt));
//    getSubject(request, response).login(new JwtToken(jwt));
        return true;
    }

    /**
     * 返回true说明有token，需要去验证
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        String authzHeader = getAuthzHeader(request);
        return authzHeader != null;
    }

    /**
     * 从请求头中获取token，生成JWT Token
     *
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        String jwt = getAuthzHeader(request);
        return new JwtToken(jwt);
    }
    protected boolean onLoginFailure(AuthenticationToken token, Exception e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setContentType("application/json; charset=utf-8");

        Throwable throwable = e.getCause() == null ? e : e.getCause();
        String msg = throwable.getLocalizedMessage();
        ResponseResult responseResult = ResponseResult.error("401", msg);
        log.info(msg);
        String json = JSONUtil.toJsonStr(responseResult);
        try {
            httpServletResponse.getWriter().print(json);
        } catch (IOException ioException) {
        }
        return false;
    }

    /**
     * 验证失败，响应前端json
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        log.info("Authentication failed: {} ,write json", e.getMessage());
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        ResponseResult.printResult(httpServletResponse, ResponseResult.error(CodeEnum.USER_TOKEN_INVALID));
        return false;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        log.info("into shiro jwt filter...");
        HttpServletRequest req = WebUtils.toHttp(request);
        HttpServletResponse res = WebUtils.toHttp(response);
        res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        res.setHeader("Access-Control-Allow-Headers", req.getHeader("Access-Control-Request-Headers"));
        //添加可以返回自定义header信息
        res.setHeader("Access-Control-Expose-Headers", jwtUtil.getHeader());
        // 跨域时会首先发送一个OPTIONS请求，这里我们给OPTIONS请求直接返回正常状态
        if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
            res.setStatus(org.springframework.http.HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }


}
